<template>
  <view class="payment-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <view class="header-left" @click="goBack">
        <text class="back-icon">←</text>
        <text class="back-text">返回</text>
      </view>
      <text class="header-title">确认入谱</text>
      <view class="header-right"></view>
    </view>

    <!-- 支付内容 -->
    <view class="payment-content">
      <!-- 待入谱成员列表 -->
      <view v-if="waitingMembers.length > 0" class="members-section">
        <view class="section-header">
          <text class="section-title">待入谱成员列表</text>
          <text class="member-count">(共{{ totalMembersCount }}人)</text>
        </view>

        <view class="members-list">
          <view v-for="member in waitingMembers" :key="member.id" class="member-item">
            <view class="member-info">
              <text class="member-name">{{ member.name }}</text>
              <view class="member-details">
                <text class="detail-item">{{ member.gender === 1 ? "男" : "女" }}</text>
                <text class="detail-item">{{ member.alive === 1 ? "在世" : "已故" }}</text>
                <text v-if="member.isSelf" class="detail-item self">本人</text>
              </view>
            </view>
            <view class="member-relation">
              <text class="relation-text">{{ member.relation }}</text>
            </view>
          </view>
        </view>

        <view class="quota-info">
          <text class="info-icon">💡</text>
          <text class="info-text">
            每位成员入谱需消耗1个指标，总计需要消耗指标数量：{{ totalMembersCount }}个
          </text>
        </view>
      </view>

      <!-- 指标消耗确认 -->
      <view class="quota-section">
        <view class="section-title">消耗指标</view>
        <view class="quota-display">
          <view class="quota-tag">
            <text class="quota-number">{{ totalMembersCount }}</text>
            <text class="quota-unit">个</text>
          </view>
          <text class="quota-text">将消耗{{ totalMembersCount }}个指标用于入谱</text>
        </view>
      </view>

      <!-- 用户额度信息 -->
      <view class="balance-section">
        <view class="section-title">当前额度</view>
        <view class="balance-info">
          <text class="balance-label">可用指标：</text>
          <text class="balance-value">{{ userQuota }}</text>
          <text class="balance-unit">个</text>
        </view>
        <view v-if="userQuota < totalMembersCount" class="insufficient-warning">
          <text class="warning-icon">⚠️</text>
          <text class="warning-text">额度不足，请先购买指标</text>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <button class="btn btn-default" @click="goBack">取消</button>
      <button
        class="btn btn-primary"
        :disabled="userQuota < totalMembersCount"
        @click="confirmPayment"
      >
        确认入谱
      </button>
    </view>
  </view>
</template>

<script>
import FamilyAPI from "@/api/genealogy/family";
import UserAPI from "@/api/system/user";

export default {
  name: "GenealogyPayment",
  data() {
    return {
      familyId: null,
      waitingMembers: [],
      totalMembersCount: 0,
      userQuota: 0,
    };
  },

  onLoad(options) {
    this.familyId = options.familyId;
    this.loadPaymentData();
  },

  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },

    // 加载支付数据
    loadPaymentData() {
      uni.showLoading({
        title: "加载中...",
      });

      // 并行加载待入谱成员和用户额度
      Promise.all([this.loadWaitingMembers(), this.loadUserQuota()]).finally(() => {
        uni.hideLoading();
      });
    },

    // 加载待入谱成员
    loadWaitingMembers() {
      return FamilyAPI.getWaitForEnterFamily(this.familyId)
        .then((data) => {
          // 处理服务器返回的数据
          this.waitingMembers = data.memberApplyPersonList.map((member) => {
            // 构建成员的显示名称（姓+名）
            const fullName = member.firstName + member.lastName;

            // 确定成员关系
            let relation = "";
            if (member.isSelf === 1) {
              relation = "本人";
            } else if (member.flag === 1) {
              relation = "配偶";
            } else {
              // 查找父亲
              const parent = data.memberApplyPersonList.find((p) => p.id === member.parentId);
              if (parent) {
                const parentName = parent.firstName + parent.lastName;
                relation = `${parentName}的${member.gender === 1 ? "儿子" : "女儿"}`;
              } else {
                relation = member.gender === 1 ? "男性亲属" : "女性亲属";
              }
            }

            return {
              id: member.id,
              name: fullName,
              gender: member.gender,
              alive: member.alive,
              relation: relation,
              isSelf: member.isSelf === 1,
            };
          });

          // 设置总成员数
          this.totalMembersCount = data.num || this.waitingMembers.length;
        })
        .catch((error) => {
          console.error("获取待入谱成员失败:", error);
          uni.showToast({
            title: "获取待入谱成员失败",
            icon: "none",
          });
        });
    },

    // 加载用户额度
    loadUserQuota() {
      return UserAPI.getProfile()
        .then((profile) => {
          this.userQuota = profile.availableQuota || 0;
        })
        .catch((error) => {
          console.error("获取用户额度失败:", error);
          this.userQuota = 0;
        });
    },

    // 确认支付
    confirmPayment() {
      if (this.userQuota < this.totalMembersCount) {
        uni.showModal({
          title: "额度不足",
          content: "您的可用指标额度不足，请前往购买。",
          confirmText: "去购买",
          cancelText: "取消",
          success: (res) => {
            if (res.confirm) {
              // 跳转到购买页面
              uni.navigateTo({
                url: "/pages/user/recharge",
              });
            }
          },
        });
        return;
      }

      uni.showModal({
        title: "确认入谱",
        content: `确定要消耗${this.totalMembersCount}个指标入谱吗？`,
        success: (res) => {
          if (res.confirm) {
            this.submitPayment();
          }
        },
      });
    },

    // 提交支付
    submitPayment() {
      uni.showLoading({
        title: "入谱中...",
      });

      FamilyAPI.doEnterFamily(this.familyId)
        .then(() => {
          uni.hideLoading();
          uni.showToast({
            title: "入谱成功，所有成员已加入家谱！",
            icon: "success",
          });

          // 延迟返回，让用户看到成功提示
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        })
        .catch((error) => {
          uni.hideLoading();
          uni.showToast({
            title: "入谱失败，请检查指标余额是否充足",
            icon: "none",
          });
          console.error("入谱失败:", error);
        });
    },
  },
};
</script>

<style scoped>
.payment-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 2rpx solid #eee;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.back-icon {
  font-size: 32rpx;
  color: #333;
}

.back-text {
  font-size: 28rpx;
  color: #333;
}

.header-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.header-right {
  width: 80rpx;
}

.payment-content {
  padding: 30rpx;
}

.members-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  align-items: center;
  gap: 10rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.member-count {
  font-size: 26rpx;
  color: #666;
}

.members-list {
  margin-bottom: 20rpx;
}

.member-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border: 2rpx solid #eee;
  border-radius: 8rpx;
  margin-bottom: 15rpx;
  background-color: #fafafa;
}

.member-info {
  flex: 1;
}

.member-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
  display: block;
}

.member-details {
  display: flex;
  gap: 15rpx;
  flex-wrap: wrap;
}

.detail-item {
  font-size: 24rpx;
  color: #666;
  padding: 4rpx 12rpx;
  background-color: #f0f0f0;
  border-radius: 20rpx;
}

.detail-item.self {
  background-color: #fff3e0;
  color: #f57c00;
}

.member-relation {
  text-align: right;
}

.relation-text {
  font-size: 26rpx;
  color: #666;
}

.quota-info {
  display: flex;
  align-items: center;
  gap: 10rpx;
  padding: 20rpx;
  background-color: #e3f2fd;
  border-radius: 8rpx;
}

.info-icon {
  font-size: 28rpx;
}

.info-text {
  font-size: 26rpx;
  color: #1976d2;
  line-height: 1.5;
}

.quota-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.quota-display {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.quota-tag {
  display: flex;
  align-items: center;
  gap: 5rpx;
  padding: 15rpx 25rpx;
  background-color: #67c23a;
  color: #fff;
  border-radius: 25rpx;
}

.quota-number {
  font-size: 36rpx;
  font-weight: bold;
}

.quota-unit {
  font-size: 28rpx;
}

.quota-text {
  font-size: 28rpx;
  color: #666;
}

.balance-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.balance-info {
  display: flex;
  align-items: center;
  gap: 10rpx;
  margin-bottom: 15rpx;
}

.balance-label {
  font-size: 28rpx;
  color: #333;
}

.balance-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #409eff;
}

.balance-unit {
  font-size: 28rpx;
  color: #666;
}

.insufficient-warning {
  display: flex;
  align-items: center;
  gap: 10rpx;
  padding: 15rpx;
  background-color: #fff3cd;
  border-radius: 8rpx;
}

.warning-icon {
  font-size: 28rpx;
}

.warning-text {
  font-size: 26rpx;
  color: #856404;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  gap: 20rpx;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-top: 2rpx solid #eee;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.btn {
  flex: 1;
  padding: 20rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  border: none;
  text-align: center;
}

.btn-primary {
  background-color: #409eff;
  color: #fff;
}

.btn-default {
  background-color: #fff;
  color: #333;
  border: 2rpx solid #ddd;
}

.btn:disabled {
  opacity: 0.5;
  pointer-events: none;
}
</style>
